package features.advance.leetcode.geometry;

/**
 * 206. 反转链表
 *
 * 难度  简单
 *
 * 反转一个单链表。
 *
 * 示例:
 *
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 * 进阶:
 * 你可以迭代或递归地反转链表。你能否用两种方法解决这道题？
 *
 */




/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution206 {

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }



    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);

        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;

        new Solution206().reverseList(listNode1);

        new Solution206(){ // 递归调用
            @Override
            public ListNode reverseList(ListNode head) {
                if (head == null) return null;
                System.out.println(head.val);
                head = head.next;
                return reverseList(head);
            }
        }.reverseList(listNode1);

        ListNode listNode = new Solution206() {
            @Override
            public ListNode reverseList(ListNode head) {
                ListNode pre = null;
                ListNode nex = head;
                while(head != null){
                   if(pre != null) {
                       pre.next = nex;
                   }
                    nex = pre;
                    pre = head;
                   head = head.next;
                }
                if(pre != null) pre.next = nex;
                return pre;
            }
        }.reverseList(listNode1);

        new Solution206(){

            public void printListNode(ListNode node){
                while(node != null){
                    System.out.println(node.val);
                    node = node.next;
                }
            }
        }.printListNode(listNode);

    }

}
